package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.LeaseSubList;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能: 添加预约订单
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/1/5 21:08
 */

public class LeaseEquipmentUpdateFragment extends Fragment {
  public static final String EXTRA_DETAIL =
      LeaseEquipmentUpdateFragment.class.getSimpleName() + ".EXTRA_DETAIL";
  public static final String EXTRA_MAINiD =
      LeaseEquipmentUpdateFragment.class.getSimpleName() + ".EXTRA_MAINiD";

  private static final int TYPE_SAVE = 2;
  private static final int REQUEST_DEVICE_TYPE = 3;
  @BindView(R.id.tv_equipmentTypeColon) TextView tvEquipmentTypeColon;
  @BindView(R.id.tv_equipmentArgsRequireColon) EditText tvEquipmentArgsRequireColon;
  @BindView(R.id.tv_leaseAmountColon) EditText tvLeaseAmountColon;
  @BindView(R.id.tv_leaseDaysColon) EditText tvLeaseDaysColon;
  @BindView(R.id.tv_leaseFeeStandardColon) EditText tvLeaseFeeStandardColon;
  @BindView(R.id.tv_leaseFeeTotalColon) EditText tvLeaseFeeTotalColon;
  @BindView(R.id.tv_earnestStarndardColon) EditText tvEarnestStarndardColon;
  @BindView(R.id.tv_earnestFeeTotalColon) EditText tvEarnestFeeTotalColon;

  private BaseVolleyActivity mActivity;

  private FragmentManager mFm;
  private LeaseSubList mItem;
  private String mId;
  private String mainId;

  public static Fragment newInstance(LeaseSubList item, String mainId) {
    LeaseEquipmentUpdateFragment fragment = new LeaseEquipmentUpdateFragment();
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_DETAIL, item);
    args.putString(EXTRA_MAINiD, mainId);
    fragment.setArguments(args);
    return fragment;
  }

  public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mItem = (LeaseSubList) getArguments().getSerializable(EXTRA_DETAIL);

    mActivity = (BaseVolleyActivity) getActivity();
    mFm = mActivity.getSupportFragmentManager();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      if (mItem == null) {
        mId = UUID.randomUUID().toString();
        actionBar.setTitle(R.string.addLeaseEquipment);
        mainId = getArguments().getString(EXTRA_MAINiD);
      } else {
        actionBar.setTitle(R.string.alterLeaseEquipment);
        mId = mItem.getId();
        mainId = mItem.getMainId();
      }
    }
    super.onCreate(savedInstanceState);
  }

  //初始化界面
  @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_lease_equipment_update, container, false);
    ButterKnife.bind(this, v);
    bindData(mItem);
    return v;
  }

  private void bindData(LeaseSubList data) {
    if (data == null) return;
    tvEquipmentTypeColon.setText(data.getDeviceType());
    tvEquipmentArgsRequireColon.setText(data.getDeviceParamRequire());
    tvLeaseAmountColon.setText(data.getLeaseNum());
    tvLeaseDaysColon.setText(data.getLeaseDays());
    tvLeaseFeeStandardColon.setText(data.getLeaseCostLevel());
    tvLeaseFeeTotalColon.setText(data.getLeaseCostTotal());
    tvEarnestStarndardColon.setText(data.getDepositStandard());
    tvEarnestFeeTotalColon.setText(data.getDepositCostTotal());
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_save_delete, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    //if (item == null) return super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        volleyPostSave();
        return true;
      case R.id.menu_item_delete:
        volleyPostDelete();
        return true;
    }

    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave() {
    if (TextUtils.isEmpty(mId)) return;
    if (mainId == null) return;
    String type = tvEquipmentTypeColon.getText().toString().trim();
    String args = tvEquipmentArgsRequireColon.getText().toString().trim();
    String amount = tvLeaseAmountColon.getText().toString().trim();
    String days = tvLeaseDaysColon.getText().toString().trim();
    String feeStandard = tvLeaseFeeStandardColon.getText().toString().trim();
    String leaseFeeTotal = tvLeaseFeeTotalColon.getText().toString().trim();
    String earnestStandard = tvEarnestStarndardColon.getText().toString().trim();
    String earnestFeeTotal = tvEarnestFeeTotalColon.getText().toString().trim();

    boolean isComplete =

        !TextUtils.isEmpty(type)
            && !TextUtils.isEmpty(args)
            && !TextUtils.isEmpty(amount)
            && !TextUtils.isEmpty(days)
            && !TextUtils.isEmpty(feeStandard)
            && !TextUtils.isEmpty(leaseFeeTotal)
            && !TextUtils.isEmpty(earnestStandard)
            && !TextUtils.isEmpty(earnestFeeTotal);
    if (!isComplete) {
      ToastUtil.show("请填写完整!");
      return;
    }

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_EQUIPMENT_UPDATE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("mainId", mainId);

    params.put("deviceType", type);
    params.put("leaseNum", amount);
    params.put("leaseDays", days);
    params.put("leaseCostLevel", feeStandard);
    params.put("leaseCostTotal", leaseFeeTotal);
    params.put("depositStandard", earnestStandard);
    params.put("depositCostTotal", earnestFeeTotal);
    params.put("deviceParamRequire", args);

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("保存失败!");
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        Base original = new Gson().fromJson(json, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show("保存成功");
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        } else {
          ToastUtil.show("保存失败!");
        }
      }
    });
    //mActivity.setResult(Activity.RESULT_OK);
    //mActivity.finish();

  }

  private void volleyPostDelete() {
    if (TextUtils.isEmpty(mId)) return;

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_EQUIPMENT_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.deleteFail);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        Base original = new Gson().fromJson(json, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show(R.string.deleteSuccess);
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        } else {
          ToastUtil.show(R.string.deleteFail);
        }
      }
    });
    //mActivity.setResult(Activity.RESULT_OK);
    //mActivity.finish();

  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_DEVICE_TYPE && data != null) {
      CustomerDialog result =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      tvEquipmentTypeColon.setText(result.getName());
    }
  }

  @OnClick(R.id.tv_equipmentTypeColon) public void onClick() {
    String orgCode =
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_LEASE_ORGCODE, "");

    BaseNetworkDialogFragment dialog = EquipmentChooseDialogFragment.newInstance(orgCode);
    dialog.setTargetFragment(this, REQUEST_DEVICE_TYPE);
    dialog.show(mActivity.getSupportFragmentManager(), "");
  }
}
